package cn.com.dhc.danlu.activity.home.wrap;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.renderscript.Int2;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.model.CategoryModel;
import cn.com.dhc.danlu.model.IChildable;
import cn.com.dhc.danlu.model.IItemable;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.SerializeCache;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.ListGridChooser;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.response.merch.CategoryListResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonConst.IntentKey.BEER_CODE;
import static cn.com.dhc.danlu.util.CommonConst.IntentKey.FOREIGN_CODE;
import static cn.com.dhc.danlu.util.CommonConst.IntentKey.RED_WINE_CODE;


/**
 * User: Geek_Soledad(wuhaiyang@danlu.com)
 * Date: 2016-08-04
 * Time: 09:10
 * Description: 首页顶部视图 封装
 */
public class CategoryHolder {
    public static final String TAG = "CategoryHolder";

    private Context ctx;
    private ListGridChooser categoryChooser;

    //    private DanluTaskProxy danluTaskProxy;

    private boolean hasInit;

    private PopupWindow pop;

    private OnItemSelectedListener onItemSelectedListener;

    private List<CategoryModel> records;

    //    public CategoryHolder(@NonNull Context ctx, DanluTaskProxy danluTaskProxy) {
    //        this.ctx = ctx;
    //        this.danluTaskProxy = danluTaskProxy;
    //    }

    public CategoryHolder(@NonNull Context ctx) {
        this.ctx = ctx;
    }

    public void setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) {
        this.onItemSelectedListener = onItemSelectedListener;
    }

    private void initChooser() {
        this.categoryChooser = new ListGridChooser(ctx);
        categoryChooser.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        categoryChooser.showAllBtn();


        categoryChooser.setOnShowAllClickListener(new ListGridChooser.OnShowAllClickListener() {
            @Override
            public void onShowAll(IChildable item, int categorySelectedIndex, int contentSelectedIndex) {
                pop.dismiss();
                agent.setFromTag(TAG);
                CategoryEvent event = new CategoryEvent(item.getCode(), item.getName());
                SerializeCache.getInstance().saveCategoryIndexs(categorySelectedIndex, -1);
                EventBus.getDefault().post(event);

            }
        });

        categoryChooser.setOnItemClickListener(new ListGridChooser.OnItemClickListener() {
            @Override
            public void onItemClick(IItemable item, IChildable parentItem, int categorySelectedIndex, int contentSelectedIndex) {
                pop.dismiss();
                String code = item.getCode();
                String text = item.getText();
                String parentCode = null;
                String firstCode = parentItem.getCode();
                agent.setFromTag(TAG);

                if (CommonConst.IntentKey.WINE_CODE.equals(firstCode) || RED_WINE_CODE.equals(firstCode) || FOREIGN_CODE.equals(firstCode) || BEER_CODE.equals(firstCode)) {
                    for (CategoryModel parent : records) {
                        if (parent.categoryModels != null && parent.categoryModels.size() > 0) {
                            for (CategoryModel child : parent.categoryModels) {
                                if (child.code == code) {
                                    code = parent.code;
                                    text = parent.getText();
                                    break;
                                }
                            }
                        }
                    }

                    if (onItemSelectedListener != null) {
                        onItemSelectedListener.onItemSelected(item, parentCode, categorySelectedIndex, contentSelectedIndex);
                    }
                    CategoryEvent event = new CategoryEvent(code, item.getCode(), text);
                    EventBus.getDefault().post(event);
                } else {
                    for (CategoryModel parent : records) {
                        if (parent.categoryModels != null && parent.categoryModels.size() > 0) {
                            for (CategoryModel child : parent.categoryModels) {
                                if (child.code == code) {
                                    //                                    code = parent.code;
                                    text = parent.getText();
                                    break;
                                }
                            }
                        }
                    }
                    parentCode = firstCode;
                    if (onItemSelectedListener != null) {
                        onItemSelectedListener.onItemSelected(item, parentCode, categorySelectedIndex, contentSelectedIndex);
                    }
                    CategoryEvent event = new CategoryEvent(code, text);
                    EventBus.getDefault().post(event);
                }
            }
        });

        hasInit = true;
        // 请求商品品类
        records = agent.getAllCategory();
        if (records == null) {
            categoryChooser.setVisibility(View.GONE);
            BaseRequest request = new BaseRequest();
            request.setToken(agent.getToken());
            agent.getApi()
                    .getAllCategory(request)
                    .compose(OperatorUtils.<CategoryListResponse>defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<CategoryListResponse>() {
                        @Override
                        protected void onSuccess(CategoryListResponse model) {
                            // 将分类数据保存到Application中
                            agent.setAllCategory(model);
                            records = agent.getAllCategory();
                            categoryChooser.setData(records);
                            categoryChooser.setVisibility(View.VISIBLE);

                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "获取商品品类失败！" : displayMessage);
                        }
                    });

        } else {
            categoryChooser.setVisibility(View.VISIBLE);
            categoryChooser.setData(records);
        }

        pop = new PopupWindow(categoryChooser, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        pop.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        pop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        pop.setFocusable(true);
        pop.setHeight(CommonUtils.getScreenHeight(ctx) - CommonUtils.dipToPx(ctx, 103) - CommonUtils.getStatusBarHeight(ctx) - 1);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setOutsideTouchable(true);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }


    public void toggleCategoryPanel(View view) {
        if (!hasInit) {
            initChooser();
        }
        if (isShowing()) {
            hide();
        } else {
            show(view);
        }
    }

    public void hide() {
        if (!hasInit) {
            initChooser();
        }
        pop.dismiss();
    }

    public void show(View view) {
        if (!hasInit) {
            initChooser();
        }
        Int2 indexs = SerializeCache.getInstance().getCategoryIndexs();
        categoryChooser.setSelectedIndexs(indexs.x, indexs.y);
        pop.showAsDropDown(view);
        backgroundAlpha(0.5f);
    }

    public boolean isShowing() {
        if (pop != null) {
            return pop.isShowing();
        } else {
            return false;
        }
    }

    public int getCategoryIndex() {
        return categoryChooser.getSelectedIndexs().x;
    }

    public int getSubCategoryIndex() {
        return categoryChooser.getSelectedIndexs().y;
    }

    public void backgroundAlpha(float bgAlpha) {
        Window window = ((Activity) pop.getContentView().getContext()).getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        window.setAttributes(lp);
    }

    public interface OnItemSelectedListener {
        void onItemSelected(IItemable item, String parentCode, int categorySelectedIndex, int contentSelectedIndex);
    }
}